export default {
  namespaced: true,
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: uni.getStorageSync('cart') || []
  }),
  mutations: {
    addToCart(state, goods) {
      const f = state.cart.find(t => t.goods_id === goods.goods_id)
      if (!f) {
        state.cart.push(goods)
      } else {
        f.goods_count++
      }
      uni.setStorageSync('cart', state.cart)
    },
    updateGoodsState(state, goods) {
      const f = state.cart.find(t => t.goods_id === goods.goods_id)
      if(f) {
        f.goods_state = goods.goods_state
      }
      uni.setStorageSync('cart', state.cart)
    }, 
    updateGoodsCount(state, goods) {
      const f = state.cart.find(t => t.goods_id === goods.goods_id)
      if(f) {
        f.goods_count = goods.goods_count
      }
      uni.setStorageSync('cart', state.cart)
    },
    // 删除商品
    deleteGoodsById(state, goods) {
      // 方式1: 
      // let index = state.cart.findIndex(t => t.goods_id === goods.goods_id)
      // if (index > -1) {
        // state.cart.slice(index, 1)
      // }
      state.cart = state.cart.filter(t => t.goods_id !== goods.goods_id)
      uni.setStorageSync('cart', state.cart)
    },
    // 更新所有商品的勾选状态
    updateAllGoodsState(state, newState) {
      state.cart.forEach(t => t.goods_state = newState)
    }
  },
  getters: {
    // 购物车商品总数
    total(state) {
      // let result = 0
      // state.cart.forEach(t => result += t.goods_count)
      // return result
      return state.cart.reduce((total, item) => total += item.goods_count, 0)
    },
    // 勾选的商品的总数量
    checkedCount(state) { 
     return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    // 已勾选的商品的总价
    checkedGoodsAmount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2)
    }
  }
}
